//
//  WSOAuthController.swift
//  微博
//
//  Created by 武莎莎 on 15/9/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

//MARK: 用户授权登录界面
class WSOAuthController: UIViewController, UIWebViewDelegate {
  
    private var webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.loadRequest(NSURLRequest(URL: WSNetworkTool.sharedNetworkTool.oauthURL))

    }
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill(){
        // js 脚本
        let js = "document.getElementById('userId').value = '793822773@qq.com';" + "document.getElementById('passwd').value = 'wss0908*';"
        // 执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    // MARK: webView代理方法
    // 在加载授权请求前拦截url,获取请求中的请求码（code），从而用来获取token值,加载用户信息
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 获取当前的请求
        let urlString = request.URL!.absoluteString
        print(urlString)
        if !urlString.hasPrefix(WSNetworkTool.sharedNetworkTool.redirecturi){
            return true
        }
        // 查询网络请求？后面的字符串以code= 开头的内容
        // request.URL?.query：获取带有code=网络请求中？后面的内容
        if let query = request.URL?.query where query.hasPrefix("code="){
            
            let code = query.substringFromIndex("code=".endIndex)
            WSUserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                    printLog(error, logError: true)
                }, completed: { () -> Void in
                    printLog("完成")
                    
                    //登陆完成要关闭控制器发一个通知
                    self.close()
                    //发通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WSSwitchRootViewControllerNotification, object: "main")
                    
            })
        }else{
            
            self.close()
        }
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
